package com.alibaba.web.config;

import com.alibaba.api.pojo.User;
import com.alibaba.api.utils.UserThreadLocal;
import io.jsonwebtoken.Jwts;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Configuration
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        User user = queryToken(token);
        if (null != user) {
            UserThreadLocal.set(user); //将当前对象，存储到当前的线程中
            return true;
        }

        //请求头中如不存在Authorization直接返回false
        response.setStatus(401); //无权限访问
        return false;
    }

    private User queryToken(String token) {
        Map<String, Object> map = Jwts.parser().setSigningKey("secret").parseClaimsJws(token).getBody();
        User user = new User();
        user.setId(Integer.parseInt(map.get("id").toString()));
        user.setId(Integer.parseInt(map.get("accountId").toString()));
        return null;
    }
}
